package compnents

import (
	"bytes"
	"centerServer/models"
	"centerServer/utils"
	"crypto/md5"
	"crypto/tls"
	"encoding/hex"
	"encoding/xml"
	"fmt"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"math/rand"
	"net/http"
	"strconv"
	"strings"
	"sync"
	"time"
)

var wxHongBaoIns *WxHongBaoCompnent
var once sync.Once

func GetWxHongBaoCompnent() *WxHongBaoCompnent {
	once.Do(func() {
		wxHongBaoIns = &WxHongBaoCompnent{}
		wxHongBaoIns.InitWxHongBaoCompnet()
	})
	return wxHongBaoIns
}

type WxHongBaoCompnent struct {
	clientIp string
}

func (this *WxHongBaoCompnent) InitWxHongBaoCompnet() {
	this.clientIp = utils.Ip()
}

var _tlsConfig *tls.Config

func getTLSConfig() (*tls.Config, error) {
	if _tlsConfig != nil {
		return _tlsConfig, nil
	}

	// load cert
	cert, err := tls.LoadX509KeyPair(WECHATCERTPATH, WECHATKEYPATH)
	if err != nil {
		fmt.Println("load wechat keys fail", err)
		return nil, err
	}

	// load root ca
	//caData, err := ioutil.ReadFile(WECHATCAPATH)
	//if err != nil {
	//	fmt.Println("read wechat ca fail", err)
	//	return nil, err
	//}
	//pool := x509.NewCertPool()
	//pool.AppendCertsFromPEM(caData)

	_tlsConfig = &tls.Config{
		Certificates: []tls.Certificate{cert},
		//RootCAs:      pool,
	}
	return _tlsConfig, nil
}

func SecurePost(url string, xmlContent []byte) (*http.Response, error) {
	tlsConfig, err := getTLSConfig()
	if err != nil {
		return nil, err
	}

	tr := &http.Transport{TLSClientConfig: tlsConfig}
	//tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
	client := &http.Client{Transport: tr}

	return client.Post(
		url,
		"text/xml",
		bytes.NewBuffer(xmlContent))
}

//  发送红包奖励 openid(用户ID) price(金额)
func (this *WxHongBaoCompnent) SendBonus(oid string, price int) {
	openid := oid                //openid
	total_amount := price * 1000 //金额

	//生成随机数并md5加密随机数
	rand.Seed(time.Now().UnixNano())
	md5Ctx1 := md5.New()
	md5Ctx1.Write([]byte(strconv.Itoa(rand.Intn(1000))))
	nonce_str := hex.EncodeToString(md5Ctx1.Sum(nil)) //随机数
	//订单号
	mch_billno := MCH_ID + time.Now().Format("20060102") + strconv.FormatInt(time.Now().Unix(), 10)
	// 参数map
	var argsKeyMap map[string]interface{}
	argsKeyMap = make(map[string]interface{})
	argsKeyMap["act_name"] = ACT_NAME
	argsKeyMap["client_ip"] = CLIENT_IP
	argsKeyMap["mch_billno"] = mch_billno
	argsKeyMap["mch_id"] = MCH_ID
	argsKeyMap["nonce_str"] = nonce_str
	argsKeyMap["re_openid"] = openid
	argsKeyMap["remark"] = REMARK
	argsKeyMap["send_name"] = SEND_NAME
	argsKeyMap["total_amount"] = strconv.Itoa(total_amount)
	argsKeyMap["total_num"] = strconv.Itoa(TOTAL_NUM)
	argsKeyMap["wishing"] = WISHING
	argsKeyMap["wxappid"] = WXAPPID
	s1 := utils.FormatSign(argsKeyMap)
	s1 += "&key=" + KEY
	//argsKeyMap["key"] = KEY
	md5Ctx2 := md5.New()
	md5Ctx2.Write([]byte(s1))
	s1 = hex.EncodeToString(md5Ctx2.Sum(nil))
	sign := strings.ToUpper(s1) //签名

	v := &models.Bonus{
		Act_name:     models.CDATA{Text: ACT_NAME},
		Client_ip:    models.CDATA{Text: CLIENT_IP},
		Mch_billno:   models.CDATA{Text: mch_billno},
		Mch_id:       models.CDATA{Text: MCH_ID},
		Nonce_str:    models.CDATA{Text: nonce_str},
		Remark:       models.CDATA{Text: REMARK},
		Send_name:    models.CDATA{Text: SEND_NAME},
		Re_openid:    models.CDATA{Text: openid},
		Total_amount: models.CDATA{Text: strconv.Itoa(total_amount)},
		Total_num:    models.CDATA{Text: strconv.Itoa(TOTAL_NUM)},
		Wishing:      models.CDATA{Text: WISHING},
		Wxappid:      models.CDATA{Text: WXAPPID},
		Sign:         models.CDATA{Text: sign}}

	output, err := xml.MarshalIndent(v, "  ", "    ")
	if err != nil {
		fmt.Printf("error: %v\n", err)
	}
	str2 := string(output[:])
	logs.Debug(str2)
	//POST数据
	httpReques, errA := SecurePost(WECHATURL, output)
	if errA != nil {
		return
	}

	defer httpReques.Body.Close()
	bodyByte, _ := ioutil.ReadAll(httpReques.Body)
	var res models.WithdrawResult
	xmlerr := xml.Unmarshal(bodyByte, &res)
	if xmlerr != nil {
		//return xmlerr.Error(), "", false
		return
	}
	//if res.ReturnCode == "SUCCESS" && res.ResultCode == "SUCCESS" {
	//	return res.PartnerTradeNo, res.PaymentNo, true
	//}

}
